package com.itheima.reggie.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPay;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.config.MyConfig;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdresService;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrdersServiceImpl implements OrdresService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public R submit(Orders orders) {
        //获得用户id,查询当前用户的购物车数据
        Long userId = BaseContext.threadLocal.get();
        LambdaQueryWrapper<ShoppingCart> cartWrapper = new LambdaQueryWrapper<>();
        cartWrapper.eq(ShoppingCart::getUserId, userId);
        //订单的明细数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(cartWrapper);
        //根据当前登录用户id,查询用户数据
        User user = userMapper.selectById(userId);
        //根据地址id,查询地址数据(获得地址)
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        //组装订单数据,批量保存订单数据  补全orders
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setAddress(addressBook.getDetail());
        orders.setAmount(sunMoney(shoppingCarts));
        orders.setConsignee(addressBook.getConsignee());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserName(user.getName());
        orderMapper.insert(orders);
        //组装保存明细数据,批量保存订单明细
        //把购物车集合转换为明细集合
        String jsonString = JSON.toJSONString(shoppingCarts);
        List<OrderDetail> orderDetails = JSON.parseArray(jsonString, OrderDetail.class);
        //封装orderId到明细中
        orderDetails.stream().forEach(c -> {
            c.setOrderId(orders.getId());
        });
        orderDetailService.saveBatch(orderDetails);
        //删除当前用户的购物车列表数据
        shoppingCartService.cleanById();
        //todo 请求微信获得支付的二维码信息
        MyConfig mc = new MyConfig();
        WXPay wxPay = null;
        try {
            wxPay = new WXPay(mc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, String> map = new HashMap<>();

        map.put("body","红烧肉套餐");
        map.put("out_trade_no",orders.getId()+"");
        map.put("total_fee","1");
        map.put("spbill_create_ip","127.0.0.1");
        //回调通知  商家接收微信的信息的接口
        map.put("notify_url","http://www.baidu.com");
        //支付类型
        map.put("trade_type","NATIVE");
        try {
            Map<String, String> responseMap = wxPay.unifiedOrder(map);
            return R.success(responseMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error("下单失败");
    }

    @Override
    public R newPage(Integer page, Integer pageSize) {

        IPage<Orders> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getCheckoutTime);
        IPage<Orders> ordersIPage = orderMapper.selectPage(p, wrapper);

        List<Orders> ordersList = ordersIPage.getRecords();
        for (Orders orders : ordersList) {
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
            orders.setOrderDetails(orderDetails);
        }
        ordersIPage.setRecords(ordersList);
        return R.success(ordersIPage);
    }

    @Override
    public R findPage(Integer page, Integer pageSize, String number, LocalDateTime beginTime, LocalDateTime endTime) {
        IPage<Orders> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        if (number != null) {
            wrapper.eq(Orders::getNumber, number);
        }
        IPage<Orders> ordersIPage = orderMapper.selectPage(p, wrapper);
        return R.success(ordersIPage);
    }

    private BigDecimal sunMoney(List<ShoppingCart> shoppingCarts) {
        BigDecimal money = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            BigDecimal amount = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            BigDecimal multiply = amount.multiply(number);
            money = money.add(multiply);
        }
        return money;
    }
}
